package com.hy.util;

import java.net.URL;

/**
 * @Author: huangya
 * @Date: 2020/5/21
 * @Description:
 */
public class ClassUtils {

    public static ClassLoader getDefaultClassLoader(){
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch(Throwable e) {

        }
        if(cl==null){
            cl = ClassUtils.class.getClassLoader();
            if (cl == null) {
                try {
                    cl = ClassLoader.getSystemClassLoader();
                }
                catch (Throwable ex) {

                }
            }
        }
        return cl;
    }

    public static URL getClassPathUrl(String path){
        ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader();
        if(defaultClassLoader==null){
            return ClassLoader.getSystemResource(path);
        }else{
            return defaultClassLoader.getResource(path);
        }
    }

    public static String getClassPath(){
        URL classPathUrl = ClassUtils.getClassPathUrl("");
        return classPathUrl==null ? null : classPathUrl.getPath();
    }

    public static Class<?> loadClass(String className) {
        Class<?> clazz = null;
        if (className == null) {
            return null;
        }

        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            // skip
        }

        ClassLoader ctxClassLoader = getDefaultClassLoader();
        if (ctxClassLoader != null) {
            try {
                clazz = ctxClassLoader.loadClass(className);
            } catch (ClassNotFoundException e) {
                // skip
            }
        }
        return clazz;
    }
}
